package com.polito.mad.bikeponyapp.activity;

import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

import com.polito.mad.bikeponyapp.R;
import com.polito.mad.bikeponyapp.persistence.DeliveriesRepository;
import com.polito.mad.bikeponyapp.persistence.DeliveryItem;
import com.polito.mad.bikeponyapp.persistence.RepositoryHolder;

public class NotificationActivity extends Activity {

	private static final String ITEM_ID_PARAM_NAME = "itemId";
	private long itemId = -1;
	private boolean isPickup = false;
	private DeliveriesRepository repository;
	private String additionalInfo;
	public static final int PICKUP_REQUEST_CODE = 1112;
	public static final int DELIVERY_REQUEST_CODE = 1113;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		repository = ((RepositoryHolder)getApplication()).getDeliveriesRepository();
		setContentView(R.layout.activity_notification);
		
		if(savedInstanceState!=null && savedInstanceState.containsKey(ITEM_ID_PARAM_NAME))
		{
			itemId = savedInstanceState.getLong(ITEM_ID_PARAM_NAME);
		}else 
		{
			Bundle bundle = getIntent().getExtras();
			if(bundle != null  && bundle.containsKey(getString(R.string.delivery_id_notification_intent_param)))
			{
				itemId = bundle.getLong(getString(R.string.delivery_id_notification_intent_param));
			}
			else//try to get it from shared preference
			{
				itemId = PreferenceManager.getDefaultSharedPreferences(this).getLong(getString(R.string.delivery_id_notification_intent_param), -1);
				
			}
		}
		
		if(itemId == -1)
		{
			removeNotificationIcon();
			
			/*
			String sTitle = "Delivery Id not correct, Please contact system administrator."; 
			TextView tv= (TextView) findViewById(R.id.notification_activity_address);
		  	tv.setText(sTitle);
		  	
		  	this.setTitle("Error ");//set the title according to the notificaiton
		  	*/
		}
		else
		{
			try {
				List<DeliveryItem> deliveryItemList = repository.findByQuery("_id="+ String.valueOf(itemId));
	   			  if(deliveryItemList!= null && deliveryItemList.size() == 1)
	   			  {
	   				  	DeliveryItem deliveryItem = deliveryItemList.get(0);
	   				  	//check if activity is visible 
						String sTitle = ""; 
					  	if(deliveryItem.getDeliveryItemType() == DeliveryItem.DeliveryItemType.DELIVERY)
					  	{
					  		sTitle = getString(R.string.notification_reached_delivery_point);
					  	}
					  	else
					  	{
					  		isPickup = true;
					  		sTitle = getString(R.string.notification_reached_pickup_point);
					  	}
					  	
					  	TextView titleTV = (TextView) findViewById(R.id.notification_activity_title);
					  	
					  	//this.setTitle(sTitle);//set the title according to the notificaiton
					  	titleTV.setText(sTitle);
					  	
					  	
					  	additionalInfo = deliveryItem.getAdditionalInfo();
						fillAdditionalInfo(); 
					  	TextView tv= (TextView) findViewById(R.id.notification_activity_address);
					  	tv.setText(deliveryItem.getAddress());
					  	
					  	
	   			  }
	   			  else
	   			  {
	   				removeNotificationIcon();
	   			  }
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		Button cancelBtn = (Button) findViewById(R.id.notification_cancel_button);
		cancelBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
						
				finish();
			}
		});
		
		/*
		boolean foregroundTest = isForeground("com.polito.mad.bikeponyapp.activity.MainActivity", context);
		if(!foregroundTest)
		{
			//Intent iT = new Intent(context, PickupActivity.class);
			Intent i = new Intent(context, MainActivity.class);
			i.setAction("showNotification");
			TaskStackBuilder.create(context)
			// Add all of this activity's parents to the back stack
					.addNextIntentWithParentStack(i)
					//.addNextIntentWithParentStack(iT)
					// Navigate up to the closest parent
					.startActivities();
		}
		*/
		Button okBtn = (Button) findViewById(R.id.notification_yes_button);
		okBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				
				
				if(isPickup)
				{
					Intent myIntent = new Intent(getApplicationContext(), PickupActivity.class );
					myIntent.putExtra(getString(R.string.delivery_id_notification_intent_param), itemId);
					startActivityForResult(myIntent, PICKUP_REQUEST_CODE);
				}
				else
				{
					Intent myIntent = new Intent(getApplicationContext(), DeliveryActivity.class );
					myIntent.putExtra(getString(R.string.delivery_id_notification_intent_param), itemId);
					startActivityForResult(myIntent, DELIVERY_REQUEST_CODE);
				}
				//saqib: there is no need to keep this visible while the other activity is launched 
				finish();
			}
		});
		
	}

	//if there is no item present in the delivery with the passed id then there is no need for the notification icon. this can be due to garbage inside bundle
	private void removeNotificationIcon()
	{
		//remove the notification icon as may be its because of some inconsistency
		PreferenceManager.getDefaultSharedPreferences(NotificationActivity.this).edit()
			.putBoolean(getString(R.string.notification_set_icon), false)
			.commit();
		
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	
	@Override
	protected void onSaveInstanceState(Bundle outState) {
		outState.putLong(ITEM_ID_PARAM_NAME, itemId);
		super.onSaveInstanceState(outState);
	}
	
	private void fillAdditionalInfo() {
		TextView tvAdditionalInfoName = (TextView) findViewById(R.id.pickup_additionalinfo_name);
		TextView tvAdditionalInfoMore = (TextView) findViewById(R.id.pickup_additionalinfo_more);
		try {
			JSONObject jo = new JSONObject(additionalInfo);
			tvAdditionalInfoName.setText(jo.get("name")+" "+jo.getString("surname"));
			String more = jo.getString("more");
			if(!more.isEmpty())
			{
				tvAdditionalInfoMore.setText(more);
			}
			else
			{
				TextView tvMoreLabel = (TextView) findViewById(R.id.pickup_additionalinfo_more_label);
				tvMoreLabel.setVisibility(View.GONE);
			}
		} catch (JSONException e) {
			//ignoring if there is no name/data
		}
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if((requestCode == PICKUP_REQUEST_CODE || requestCode == DELIVERY_REQUEST_CODE) && resultCode == Activity.RESULT_OK)
		{
			setResult(RESULT_OK);
			finish();
		}
	}
	

}
